package com.toman.ui.work.workshop;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.request.PostRequest;
import com.toman.Enum.BaseEnum;
import com.toman.Enum.NetworkEnum;
import com.toman.Enum.PermEnum;
import com.toman.Enum.TimeEnum;
import com.toman.Enum.ViewTypeEnum;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.JavaBean.BeltlineEntity;
import com.toman.JavaBean.NoplanReportDto;
import com.toman.R;
import com.toman.Util.JsonExcludeNull;
import com.toman.Util.PermissonUtils;
import com.toman.Util.SPUtils;
import com.toman.Util.TimeUtil;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.bean.ItemListBean;
import com.toman.bean.TemplateInfBean;
import com.toman.bean.TemplateInfBeanPreHandler;
import com.toman.camera.Camera;
import com.toman.templateActivity.controler.TempFoldAdapter;
import com.toman.templateActivity.controler.TempInfAdapter;
import com.toman.templateActivity.controler.TempView;
import com.toman.toolbar.ToolBarActivity;
import com.toman.widget.callback.http.AddCallback;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Request;
import okhttp3.Response;

public class NoPlanSubmitInfActivity extends ToolBarActivity {
    @BindView(R.id.ll)
    LinearLayout ll;
    private TempInfAdapter adapter;
    List<TemplateInfBean> list = new ArrayList<>();
    List<TemplateInfBean> list_other = new ArrayList<>();
    List<TemplateInfBean> list_audit = new ArrayList<>();
    NoplanReportDto bean;
    private TempFoldAdapter foldAdapter;
    private TempFoldAdapter foldOtherAdapter;
    private TempFoldAdapter foldAuditAdapter;

    Camera camera;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_template_inf);
        ButterKnife.bind(this);
        initIntent();
        initView();


    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.toolbar_edit, menu);


        MenuItem menuItem = menu.findItem(R.id.menu_edit);
//        还没配置权限
        if (status.equals("1")|| !PermissonUtils.contains(getApplicationContext(), baseEnum.has(PermEnum.EDIT))) {
            menuItem.setVisible(false);
        }
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {

            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_edit:
                        if (item.getTitle().equals("编辑")) {
                            item.setTitle("完成");
                            adapter.refresh(true);
                            camera = list.get(13).getCamera();
                        }
                        else {
//                            item.setTitle("编辑");
//                            adapter.refresh(false);
//                            camera = list.get(13).getCamera();
                            add();


                        }
//                        if (adapter.isEdit()){
////                            add();
//                        }


//                        add();
                        break;
                }
                return false;
            }
        });

        return true;
    }

    private void initView() {
        baseEnum = BaseEnum.NOPLANSUBMIT;
        initToolBar(baseEnum.detail());
        TemplateInfBean depBean = new TemplateInfBean("departmentId", "部门名称", bean.getDepartmentEntity().getDepartmentName(), bean.getDepartmentId() + "", ViewTypeEnum.CLICK, NetworkEnum.DEP, mCompanyId, false, true, true);
        TemplateInfBean shiftBean = new TemplateInfBean("shiftId", "班次", bean.getShiftEntity().getShiftName(), bean.getShiftId() + "", ViewTypeEnum.CLICK, NetworkEnum.SHIFTANDTIME, mCompanyId, false, true, true) {
            @Override
            public void doAction(TemplateInfBean observable, TemplateInfBean listener) {
                super.doAction(observable, listener);
                Map<String, String> map = new HashMap<String, String>();
                map.put("departmentId", observable.getResult());
                listener.setMap(map);
                adapter.refresh();
            }
        };
        shiftBean.getList_keys().add("isToday");
        shiftBean.getList_keys().add("endTime");


        depBean.getListeners().add(shiftBean);
        TemplateInfBean endBean = new TemplateInfBean("endDate", "截止时间", bean.getEndDate(), bean.getEndDate(), ViewTypeEnum.DATE, TimeEnum.BOTH, false, true, true) {
            @Override
            public void doAction(TemplateInfBean observable, TemplateInfBean listener) {
                super.doAction(observable, listener);
//                通过班次判断是否隔天 带出截止时间
                if (observable.getList_get().get(0) == null || observable.getList_get().get(0).equals("0")) {
                    listener.setContent(TimeUtil.getNowTimeNew() + " " + observable.getList_get().get(1));
                    listener.setResult(TimeUtil.getNowTimeNew() + " " + observable.getList_get().get(1));

                } else if (observable.getList_get().get(0).equals("1")) {
                    listener.setContent(TimeUtil.getNowTimeAddOneDay() + " " + observable.getList_get().get(1));
                    listener.setResult(TimeUtil.getNowTimeAddOneDay() + " " + observable.getList_get().get(1));
                }
                adapter.refresh();
            }

        };
        shiftBean.getListeners().add(endBean);

        TemplateInfBean productBean = new TemplateInfBean("productId", "品名", bean.getProductEntity().getProductName(), bean.getProductId() + "", ViewTypeEnum.CLICK, NetworkEnum.PRODUCT, mCompanyId, true, true, false);
        productBean.getList_keys().add("productMode");
        TemplateInfBean typeBean = new TemplateInfBean(null, "型号", bean.getProductEntity().getProductMode(), null, ViewTypeEnum.TEXT, NetworkEnum.PRODUCT, mCompanyId, false, false, false) {
            @Override
            public void doAction(TemplateInfBean observable, TemplateInfBean listener) {
                super.doAction(observable, listener);
                if (observable.getList_get().get(0) != null) {
                    listener.setContent(observable.getList_get().get(0));
                } else {
                    listener.setContent("");
                }
                adapter.refresh();

            }
        };
        productBean.getListeners().add(typeBean);
        productBean.getList_keys().add("artlineId");

        TemplateInfBean orderBean = new TemplateInfBean("orderId", "工序名称", bean.getOrderEntity().getOrderName(), bean.getOrderId() + "", ViewTypeEnum.CLICK, NetworkEnum.ORDER, mCompanyId, false, true, false) {
            @Override
            public void doAction(TemplateInfBean observable, TemplateInfBean listener) {
                super.doAction(observable, listener);
                if (observable == productBean) {
                    Map<String, String> map = new HashMap<String, String>();
                    if (observable.getList_get().get(1) != null)
                        map.put("artlineId", observable.getList_get().get(1));
                    listener.setMap(map);
                    adapter.refresh();
                }
            }
        };
        productBean.getListeners().add(orderBean);
        orderBean.getList_keys().add("beltlineEnties");
        TemplateInfBean beletBean = new TemplateInfBean("beltlineId", "产线名称", bean.getBeltlineEntity().getBeltlineName(), bean.getBeltlineId() + "", ViewTypeEnum.CLICK, NetworkEnum.BELTLINE, mCompanyId, false, true, true) {
            @Override
            public void doAction(TemplateInfBean observable, TemplateInfBean listener) {
                super.doAction(observable, listener);
                if (observable == depBean) {
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("departmentId", observable.getResult());
                    listener.setMap(map);
                }
                if (observable == orderBean) {
                    if (observable.getList_get().get(0) != null) {
                        List<BeltlineEntity> jsonArray = new ArrayList<>(JsonExcludeNull.parseArrayExcludeNull(observable.getList_get().get(0), BeltlineEntity.class));
                        List<ItemListBean> itemListBeans = new ArrayList<>();
                        for (BeltlineEntity entity : jsonArray) {
                            itemListBeans.add(new ItemListBean(entity.getBeltlineName(), entity.getId() + ""));
                        }

                        listener.setItemListBeans(itemListBeans);

                    }

                }
                adapter.refresh();
            }

        };
        TemplateInfBean manBean = new TemplateInfBean("opUserId", "操作工", bean.getOpUser().getRealName(), bean.getOpUserId() + "", ViewTypeEnum.CLICK, NetworkEnum.OPERATOR, mCompanyId, false, true, true) {
            @Override
            public void doAction(TemplateInfBean observable, TemplateInfBean listener) {
                super.doAction(observable, listener);
                if (observable == beletBean) {
                    Map<String, String> map = new HashMap<String, String>();
                    if (observable.getResult() != null)
                        map.put("beltlineId", observable.getResult());
                    listener.setMap(map);
                    adapter.refresh();
                }
            }
        };
        beletBean.getListeners().add(manBean);

        orderBean.getListeners().add(beletBean);
        depBean.getListeners().add(beletBean);
        depBean.getListeners().add(manBean);
        depBean.getPreHandlers().add(new TemplateInfBeanPreHandler() {
            @Override
            public boolean preHandle() {
                for (TemplateInfBean templateInfBean : depBean.getListeners()) {
                    templateInfBean.setResult(null);
                    templateInfBean.setContent(null);
                }
                beletBean.setResult(null);
                beletBean.setContent(null);
                adapter.refresh();
                return true;
            }
        });
        beletBean.getPreHandlers().add(new TemplateInfBeanPreHandler() {
            @Override
            public boolean preHandle() {
                for (TemplateInfBean templateInfBean : beletBean.getListeners()) {
                    templateInfBean.setResult(null);
                    templateInfBean.setContent(null);
                }
                adapter.refresh();
                return true;
            }
        });
        list.add(depBean);
        list.add(new TemplateInfBean("reportDate", "日期", bean.getReportDate(), bean.getReportDate(), ViewTypeEnum.DATE, TimeEnum.DATE, false, true, true));
        list.add(shiftBean);
        list.add(endBean);
        list.add(new TemplateInfBean(null, "采集数", bean.getGatherCount() + "", bean.getGatherCount() + "", ViewTypeEnum.EDIT, InputType.TYPE_CLASS_NUMBER, false, false, false));
        list.add(productBean);
        list.add(typeBean);
        list.add(orderBean);
        list.add(beletBean);
        list.add(manBean);
        list.add(new TemplateInfBean("completedCount", "提交完工数", bean.getCompletedCount() + "", bean.getCompletedCount() + "", ViewTypeEnum.EDIT, InputType.TYPE_CLASS_NUMBER, false, true, true));
        list.add(new TemplateInfBean("qualifiedCount", "提交合格数", bean.getQualifiedCount() + "", bean.getQualifiedCount() + "", ViewTypeEnum.EDIT, InputType.TYPE_CLASS_NUMBER, false, true, true));
        list.add(new TemplateInfBean("addDesc", "备注", bean.getAddDesc(), bean.getAddDesc(), ViewTypeEnum.EDITMORE, true, true, false));
        list.add(new TemplateInfBean("remark", "产品图片或截图", null, null, ViewTypeEnum.PHOTO, null, this, true, true, false));
        list.get(13).setProblemImageList(bean.getImages());
        foldAdapter = new TempFoldAdapter(list, "报工信息", false);

        list_other.add(new TemplateInfBean(null, "报工人", bean.getCreateUser().getRealName(), null, ViewTypeEnum.TEXT, InputType.TYPE_CLASS_NUMBER, false, false, false));
        list_other.add(new TemplateInfBean(null, "报工时间", bean.getCreateTime(), null, ViewTypeEnum.TEXT, InputType.TYPE_CLASS_NUMBER, false, false, false));
        list_other.add(new TemplateInfBean(null, "修改人", bean.getUpdateUser().getRealName(), null, ViewTypeEnum.TEXT, InputType.TYPE_CLASS_NUMBER, false, false, false));
        list_other.add(new TemplateInfBean(null, "修改时间", bean.getUpdateTime(), null, ViewTypeEnum.TEXT, InputType.TYPE_CLASS_NUMBER, false, false, false));
        foldOtherAdapter = new TempFoldAdapter(list_other, "其他信息", true);
        if (status.equals("0")) {
            adapter = new TempInfAdapter(this, ll, Arrays.asList(foldAdapter, foldOtherAdapter));
        }
        list_audit.add(new TemplateInfBean(null, "审核完工数", bean.getVerifyCompletedCount() + "", null, ViewTypeEnum.TEXT, InputType.TYPE_CLASS_NUMBER, false, true, true));
        list_audit.add(new TemplateInfBean(null, "审核合格数", bean.getVerifyQualifiedCount() + "", null, ViewTypeEnum.TEXT, InputType.TYPE_CLASS_NUMBER, false, true, true));
        list_audit.add(new TemplateInfBean(null, "审核人", bean.getAuditUser().getRealName(), null, ViewTypeEnum.TEXT, InputType.TYPE_CLASS_NUMBER, false, false, false));
        list_audit.add(new TemplateInfBean(null, "审核时间", bean.getAuditTime(), null, ViewTypeEnum.TEXT, InputType.TYPE_CLASS_NUMBER, false, false, false));
        foldAuditAdapter = new TempFoldAdapter(list_audit, "审核信息", true);
        if (status.equals("1")) {
            adapter = new TempInfAdapter(this, ll, Arrays.asList(foldAdapter, foldOtherAdapter,foldAuditAdapter));
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        camera = list.get(13).getCamera();

        camera.onActivityResult(requestCode, resultCode, data);
    }
    private void initIntent() {
        bean = (NoplanReportDto) getIntent().getSerializableExtra("bean");
        status = getIntent().getStringExtra("status");
    }

    public void add() {
        camera = list.get(13).getCamera();

        if (dialog != null) {
            dialog.dismiss();
        }
        if (adapter.isNull()){return;};
        if (TempView.compareString(this,list.get(9),list.get(10) )
                ) {
            return;
        }

        PostRequest request = OkHttpUtils
                .post(NewBaseUrl.devicehouse_noplanreport_update)
                .headers("User-Agent","Android")
                .headers("Content-Type", "multipart/form-data")
                .headers("token", this.token)
                .params("id",bean.getId()+"")
                ;

        for (TemplateInfBean bean :list){
            if (bean.getName()!=null&&bean.getType()!=ViewTypeEnum.PHOTO){
                request.params(bean.getName(),bean.getResult());
            }
            else if (bean.getType()==ViewTypeEnum.PHOTO){
                request .addFileParams("file",ViewUtil.getFiles(camera));
                request .params("deleteUrls", ViewUtil.getDeleteUrl(camera));

            }
        }
        request  .execute(new AddCallback(this) {
            @Override
            public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                Log.i("test", ": " + result);

                JSONObject jsonObj = JSON.parseObject(result);
                int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());

                if (code == 0) {
                    ToastUtil.makeText(getApplicationContext(), jsonObj.getString("msg"));
//                            ToastUtil.makeText(getApplicationContext(),"获取wifi信号强度成功，状态约30s后会更新");
                    finish();


                } else {
                    ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                }

            }
        });
    }

}
